import React from 'react'
import { Table, Tag, Space, Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { connect } from 'dva'
import ExportJsonExcel from "js-export-excel"
import XLSX from 'xlsx'
const columns = [
    {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
    }
]


function About({ about, connectList }) {
    // 导入

    function beforeUpload(file) {
        return new Promise((reslove, reject) => {
            if (reslove) analysis(file)
        })
    }

    // 解析
    function analysis(file) {
        return new Promise((reslove, reject) => {
            let fileRead = new FileReader()
            fileRead.onload = (excel) => {
                let excelInfo = XLSX.read(excel.currentTarget.result, { type: 'binary' })
                let arr = XLSX.utils.sheet_to_json(excelInfo.Sheets["第一页"])
                connectList(arr)
            }
            // 为了执行onload
            fileRead.readAsBinaryString(file)
        })
    }


    // 导出
    var option = {};

    option.fileName = "统计";

    option.datas = [
        {
            sheetData: about,
            sheetName: "第一页",
            sheetFilter: ["name", "age"],
            sheetHeader: ["姓名", "年龄"]
        }
    ];

    const props = {
        accept: '.xlsx',
        action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    };

    return (
        <div>
            <Button onClick={() => {
                var toExcel = new ExportJsonExcel(option); //new
                toExcel.saveExcel(); //保存
            }} type="primary">导出</Button>

            <Upload beforeUpload={beforeUpload} {...props}>
                <Button icon={<UploadOutlined />}>导入</Button>
            </Upload>,

            <Table columns={columns} dataSource={about} />
        </div>
    )
}

const mapState = (state) => {
    const { about } = state
    return {
        about
    }
}

const mapDispatch = (dispatch) => {
    return {
        connectList(list) {
            dispatch({ type: "about/connect", list})
        }
    }
}

About = connect(mapState, mapDispatch)(About)

export default About
